package com.jacobson.huobi.utils

import io.reactivex.BackpressureStrategy
import io.reactivex.Flowable
import io.reactivex.FlowableEmitter
import okhttp3.OkHttpClient
import okhttp3.Request
import okio.Okio
import java.io.File

object DownLoadUtil {
    fun download(url: String?, savePath: String?): Flowable<Int?> {
        return Flowable.create({ emitter: FlowableEmitter<Int?> ->
            val request = Request.Builder().url(url).build()
            val response = OkHttpClient().newCall(request).execute()
            val saveFile = File(savePath)
            val saveDir =
                saveFile.parentFile ?: throw IllegalStateException("Find save dir $saveFile fail!")
            if (!saveDir.exists()) {
                check(saveDir.mkdirs()) { "Create save dir $saveFile fail!" }
            }
            val body = response.body()
            var current: Long = 0
            val total = body!!.contentLength()
            val bufferSize = 200 * 1024 //200kb
            val sink = Okio.buffer(Okio.sink(saveFile))
            val source = body.source()
            val buffer = sink.buffer()
            var len: Long
            while (source.read(buffer, bufferSize.toLong()).also { len = it } != -1L) {
                if (!emitter.isCancelled) {
                    current += len
                    val progress = (current * 100 / total).toInt()
                    emitter.onNext(progress)
                }
            }
            source.close()
            sink.close()
            if (!emitter.isCancelled) {
                emitter.onComplete()
            }
        }, BackpressureStrategy.LATEST)
    }
}